<template>
  <!-- 新增规则 表单 -->
  <a-modal
    v-model:open="visible"
    :title="title"
    @ok="handleOk"
    class="addStation"
    destroyOnClose
    :width="800"
    @cancel="cancel"
    centered
  >
    <a-form
      :model="form"
      :rules="rules"
      layout="inline"
      :labelCol="labelCol"
      ref="formRef"
      :disabled="props.isInfo"
    >
      <div class="titleContent">
        <div class="title">基础信息配置</div>
        <div class="subTitle">用于电价时段规则的基础信息</div>
      </div>
      <a-form-item label="电价时段规则名称" name="name">
        <a-input
          v-model:value="form.name"
          class="formInput"
          placeholder="请输入"
        />
      </a-form-item>
      <a-form-item label="适用省份：" name="provId">
        <a-select
          ref="select"
          v-model:value="form.provId"
          class="formInput"
          placeholder="省份"
          show-search
          optionFilterProp="label"
          @change="changeProv"
        >
          <a-select-option
            v-for="item in provList"
            :key="item.provId"
            :value="item.provId"
            :label="item.provName"
          >
            {{ item.provName }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="备注：">
        <a-input
          v-model:value="form.comment"
          class="formInput"
          placeholder="请输入"
        />
      </a-form-item>
      <a-form-item label="执行时间：" name="startEndTimes">
        <a-button @click="showDate = true">新增时间</a-button>
        <div class="addDate" v-if="showDate">
          <a-range-picker
            v-model:value="date"
            value-format="YYYY-MM-DD"
            format="YYYY-MM-DD"
            :allowClear="false"
            separator="~"
          />
          <CheckOutlined @click="handleSaveDate" class="handleSaveDate" />
        </div>
        <div class="tagConent">
          <a-tag
            v-for="(item, index) in form.startEndTimes"
            :key="item"
            :closable="!props.isInfo"
            @close="handleCloseDate(index)"
            >{{ prefixDate(item) }}
          </a-tag>
        </div>
      </a-form-item>
      <div class="titleContent">
        <div class="title">电价时段规则配置</div>
        <div class="subTitle">用于配置尖峰平谷时段及对应电价</div>
      </div>
      <a-form-item label="时段设置" name="timeQuantum">
        <a-select
          ref="select"
          v-model:value="form.timeQuantum"
          class="formInput"
          placeholder="选择时段"
          show-search
          optionFilterProp="label"
          @change="changeDateRange"
        >
          <a-select-option :value="1">1小时</a-select-option>
          <a-select-option :value="0">30分钟</a-select-option>
        </a-select>
      </a-form-item>

      <div class="rangeTitle">请选择时段，并在下方标注出来</div>
      <a-form-item label="">
        <EditOutlined
          :class="['editIcon', selectPen === 'jian' ? 'jianPen' : '']"
          @click="handleSelectPen('jian')"
        />
        <div class="dateLabel">
          <div class="labelIdon jianBg" />
          尖期
        </div>
        <a-input-number
          v-model:value="form.superPeakPrice"
          addon-after="元/kWh"
          class="priceInput"
          placeholder="请输入尖期电价"
          :controls="false"
        />
      </a-form-item>
      <a-form-item label="" name="peakPrice">
        <EditOutlined
          :class="['editIcon', selectPen === 'feng' ? 'fengPen' : '']"
          @click="handleSelectPen('feng')"
        />
        <div class="dateLabel">
          <div class="labelIdon fengBg" />
          峰期
        </div>
        <a-input-number
          v-model:value="form.peakPrice"
          addon-after="元/kWh"
          class="priceInput"
          placeholder="请输入峰期电价"
          :controls="false"
        />
      </a-form-item>
      <a-form-item label="" name="flatPrice">
        <EditOutlined
          :class="['editIcon', selectPen === 'ping' ? 'pingPen' : '']"
          @click="handleSelectPen('ping')"
        />
        <div class="dateLabel">
          <div class="labelIdon pingBg" />
          平期
        </div>
        <a-input-number
          v-model:value="form.flatPrice"
          addon-after="元/kWh"
          class="priceInput"
          placeholder="请输入平期电价"
          :controls="false"
        />
      </a-form-item>
      <a-form-item label="" name="valleyPrice">
        <EditOutlined
          :class="['editIcon', selectPen === 'gu' ? 'guPen' : '']"
          @click="handleSelectPen('gu')"
        />
        <div class="dateLabel">
          <div class="labelIdon guBg" />
          谷期
        </div>
        <a-input-number
          v-model:value="form.valleyPrice"
          addon-after="元/kWh"
          class="priceInput"
          placeholder="请输入谷期电价"
          :controls="false"
        />
      </a-form-item>
      <a-form-item label="">
        <EditOutlined
          :class="['editIcon', selectPen === 'shengu' ? 'shenguPen' : '']"
          @click="handleSelectPen('shengu')"
        />
        <div class="dateLabel">
          <div class="labelIdon shenguBg" />
          深谷
        </div>
        <a-input-number
          v-model:value="form.deepValleyPrice"
          addon-after="元/kWh"
          class="priceInput"
          placeholder="无该规则时段无需填写"
          :controls="false"
        />
      </a-form-item>
      <a-form-item label="" name="hourList">
        <div
          class="dateTable"
          @mousedown="startDrawing"
          @mouseup="stopDrawing"
          @mouseleave="stopDrawing"
          @mousemove="draw"
        >
          <div
            :class="['cell', item.type]"
            v-for="(item, index) in hourList"
            :key="item.value"
          >
            <span>{{ item.value }}</span>
          </div>
        </div>
      </a-form-item>
    </a-form>

    <template #footer>
      <!-- 新增 -->
      <div class="footerBar" v-if="isAdd || isEdit">
        <a-button key="back" @click="cancel">取消</a-button>
        <a-button
          key="submit"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确认</a-button
        >
      </div>
      <!-- 编辑 删除 复制新增 -->
      <div class="footerBar" v-if="isInfo">
        <a-button type="primary" @click="handleEdit">编辑</a-button>
        <a-popconfirm ok-text="确认" cancel-text="取消" @confirm="confirmDel">
          <template #title>
            是否确定删除【{{ rowData.name }}】这条规则?
          </template>
          <a-button type="primary" danger>删除规则</a-button>
        </a-popconfirm>
        <a-button type="primary" class="greenBtn" @click="handleCopy"
          >复制新增</a-button
        >
      </div>
    </template>
  </a-modal>
</template>
<script setup>


import { HOUR_LIST, HALF_HOUR_LIST } from "@/constants/dispatchCenter";
import { isArray, isObject } from "lodash-es";
import dayjs from "dayjs";
const $api = inject("$api");
const props = defineProps({
  addRuleVisible: {
    type: Boolean,
    default: false,
  },
  rowData: {
    type: Object,
  },
  isAdd: {
    type: Boolean,
    default: false,
  },
  isInfo: {
    type: Boolean,
    default: false,
  },
  isEdit: {
    type: Boolean,
    default: false,
  },
  provList: {
    type: Array,
  },
});
const loading = ref(false);
const visible = ref(props.addRuleVisible);
const emits = defineEmits([
  "update:addRuleVisible",
  "update:isAdd",
  "update:isInfo",
  "update:isEdit",
  "getElecRule",
]);
const title = computed(() => {
  if (props.isInfo) {
    return "查看电价时段规则";
  } else if (props.isEdit) {
    return "编辑电价时段规则";
  } else if (props.isAdd) {
    return "新增电价时段规则";
  }
});
watch(
  () => props.addRuleVisible,
  (val) => {
    visible.value = val;
    if (val) {
      changeDateRange(form.value.timeQuantum); // 初始化时段
      if (props.isInfo) {
        form.value = {
          ...props.rowData,
        };
        changeDateRange(form.value.timeQuantum); // 有默认数据时，再根据时段选择时间范围重置时段list
        // 定义时间范围映射
        const timeRangeMappings = [
          { key: "superPeakTimeRange", type: "jian" },
          { key: "peakTimeRange", type: "feng" },
          { key: "flatTimeRange", type: "ping" },
          { key: "valleyTimeRange", type: "gu" },
          { key: "deepValleyTimeRange", type: "shengu" },
        ];
        // 处理每个时间范围字段
        timeRangeMappings.forEach((mapping) => {
          const ranges = props.rowData[mapping.key].split(",").filter(Boolean);
          ranges.forEach((range) => {
            const normalizedRange = range.trim();
            const hourObject = hourList.value.find(
              (hour) => hour.value === normalizedRange
            );
            if (hourObject) {
              hourObject.type = mapping.type; // 设置对应的类型，即对应的颜色
            }
          });
        });
      }
    }
  }
);
const hourList = ref([]);
const labelCol = { style: { width: "140px" } };
const formRef = ref(null);
const date = ref();
const showDate = ref(false);
const form = ref({
  name: undefined,
  provId: undefined,
  comment: undefined,
  startEndTimes: [],
  timeQuantum: 1,
  superPeakPrice: undefined,
  superPeakTimeRange: "",
  peakPrice: undefined,
  peakTimeRange: "",
  flatPrice: undefined,
  flatTimeRange: "",
  valleyPrice: undefined,
  valleyTimeRange: "",
  deepValleyPrice: undefined,
  deepValleyTimeRange: "",
});
const rules = ref({
  name: [
    {
      required: true,
      message: "请输入",
      trigger: "blur",
    },
  ],
  provId: [
    {
      required: true,
      message: "请选择",
      trigger: "blur",
    },
  ],
  timeQuantum: [
    {
      required: true,
      message: "请选择",
      trigger: "change",
    },
  ],
  peakPrice: [
    {
      required: true,
      message: "请输入",
      trigger: "blur",
    },
  ],
  flatPrice: [
    {
      required: true,
      message: "请输入",
      trigger: "blur",
    },
  ],
  valleyPrice: [
    {
      required: true,
      message: "请输入",
      trigger: "blur",
    },
  ],
  startEndTimes: [
    {
      required: true,
      message: "请选择",
      trigger: "blur",
      validator: (rule, value) => {
        if (form.value.startEndTimes.length === 0) {
          return Promise.reject('请选择执行时间');
        } else {
          return Promise.resolve();
        }
      },
    },
  ],
  hourList: [
    {
      required: true,
      trigger: "change",
      validator: (rule, value) => {
        if (hourList.value.some((item) => item.type === "")) {
          return Promise.reject('请标注所有时段');
        } else {
          return Promise.resolve();
        }
      },
    },
  ],
});

const cancel = () => {
  emits("update:addRuleVisible", false);
  emits("update:isInfo", false);
  emits("update:isEdit", false);
  form.value = {
    name: undefined,
    provId: undefined,
    comment: undefined,
    startEndTimes: [],
    timeQuantum: 1,
    superPeakPrice: undefined,
    superPeakTimeRange: "",
    peakPrice: undefined,
    peakTimeRange: "",
    flatPrice: undefined,
    flatTimeRange: "",
    valleyPrice: undefined,
    valleyTimeRange: "",
    deepValleyPrice: undefined,
    deepValleyTimeRange: "",
  };
  formRef.value.clearValidate();
};
const handleSaveDate = () => {
  if (date.value?.length > 0) {
    form.value.startEndTimes.push(date.value);
    showDate.value = false;
    date.value = [];
    formRef.value.validateFields("startEndTimes");
  }
};
const prefixDate = (value) => {
  if (isArray(value)) {
    let date1 = value[0];
    let date2 = value[1];
    return date1 + "~" + date2;
  }
  if (isObject(value)) {
    let date1 = value.startTime;
    let date2 = value.endTime;
    return date1 + "~" + date2;
  }
};
const handleCloseDate = (index) => {
  form.value.startEndTimes.splice(index, 1);
};
const drawing = ref(false);
const startDrawing = () => {
  if (!props.isInfo) {
    drawing.value = true;
  }
};
const stopDrawing = () => {
  drawing.value = false;
  if (!props.isInfo) {
    formRef.value.validateFields("hourList");
  }
};
const draw = (event) => {
  if (!drawing.value) return;
  const grid = event.currentTarget;
  const rect = grid.getBoundingClientRect();
  const x = event.clientX - rect.left; // 鼠标 x 坐标
  const y = event.clientY - rect.top; // 鼠标 y 坐标
  const col = Math.floor(x / 93.75); // 列数
  const row = Math.floor(y / 28); // 行数
  const index = row * 8 + col; // 计算索引
  if (index >= 0 && index < hourList.value.length) {
    hourList.value[index].type = selectPen.value;
  }
};
const changeDateRange = (value) => {
  if (value === 1) {
    hourList.value = HOUR_LIST.map((item) => {
      return {
        value: item,
        type: "",
      };
    });
  } else {
    hourList.value = HALF_HOUR_LIST.map((item) => {
      return {
        value: item,
        type: "",
      };
    });
  }
};
const selectPen = ref();
const handleSelectPen = (value) => {
  if (props.isInfo) {
    return;
  }
  if (selectPen.value === value) {
    selectPen.value = "";
  } else {
    selectPen.value = value;
  }
};
const handleEdit = (data) => {
  emits("update:isAdd", false);
  emits("update:isEdit", true);
  emits("update:isInfo", false);
};
const confirmDel = async () => {
  const res = await $api.delElecRule(props.rowData.id);
  if (res.code === 0) {
    message.success("删除成功");
    emits("getElecRule");
    cancel();
  }
};
const handleCopy = () => {
  emits("update:isAdd", true);
  emits("update:isEdit", false);
  emits("update:isInfo", false);
};
const handleSubmit = () => {
  formRef.value
    .validate()
    .then(async () => {
      let superPeakTimeRange = [];
      let peakTimeRange = [];
      let flatTimeRange = [];
      let valleyTimeRange = [];
      let deepValleyTimeRange = [];
      for (const item of hourList.value) {
        switch (item.type) {
          case "jian":
            superPeakTimeRange.push(item.value);
            break;
          case "feng":
            peakTimeRange.push(item.value);
            break;
          case "ping":
            flatTimeRange.push(item.value);
            break;
          case "gu":
            valleyTimeRange.push(item.value);
            break;
          case "shengu":
            deepValleyTimeRange.push(item.value);
            break;
          default:
            break;
        }
      }

      const params = {
        ...form.value,
        // startEndTimes: form.value.startEndTimes,
        superPeakTimeRange: superPeakTimeRange.join(","),
        peakTimeRange: peakTimeRange.join(","),
        flatTimeRange: flatTimeRange.join(","),
        valleyTimeRange: valleyTimeRange.join(","),
        deepValleyTimeRange: deepValleyTimeRange.join(","),

        superPeakPrice: form.value.superPeakPrice?.toString(),
        peakPrice: form.value.peakPrice?.toString(),
        flatPrice: form.value.flatPrice?.toString(),
        valleyPrice: form.value.valleyPrice?.toString(),
        deepValleyPrice: form.value.deepValleyPrice?.toString(),
      };
      let res;
      params.startEndTimes = form.value.startEndTimes.map((item) => {
        if (isArray(item)) {
          return {
            startTime: item[0],
            endTime: item[1],
          };
        }
        if (isObject(item)) {
          return {
            startTime: item.startTime,
            endTime: item.endTime,
          };
        }
      });
      loading.value = true;
      if (props.isEdit) {
        // 编辑带上id
        params.id = props.rowData.id;
        res = await $api.editElecRule(params);
        console.log('[ params ]-589', params)
        loading.value = false;
        if (res.code === 0) {
          message.success("编辑成功");
          emits("getElecRule");
          cancel();
        }
      } else {
        res = await $api.addElecRule(params);
        loading.value = false;
        if (res.code === 0) {
          message.success("新增成功");
          emits("getElecRule");
          cancel();
        }
      }
    })
    .catch((error) => {
      console.log("error", error);
    });
};
</script>

<style lang="less" scoped>
.form {
  padding: 0 40px;
  margin-top: 30px;
}
.formInput,
.formSelect {
  width: 611px;
}
.ant-form-item {
  margin-top: 20px;
  width: 100%;
}
.footerBar {
  text-align: center;
  margin-top: 30px;
}
.titleContent {
  width: 100%;
  margin-top: 30px;
  .title {
    font-weight: 700;
    display: inline-block;
    margin-right: 20px;
  }
  .subTitle {
    font-size: 12px;
    color: #999;
    display: inline-block;
  }
}
.addDate {
  margin-top: 10px;
}
.handleSaveDate {
  margin-left: 10px;
  font-size: 16px;
}
.tagConent {
  width: 390px;
}
.ant-tag {
  margin-top: 10px;
  display: inline-block;
}
.rangeTitle {
  width: 100%;
  font-size: 12px;
  color: #999;
  margin: 30px 0 0 0;
}
.dateLabel {
  width: 80px;
  height: 32px;
  line-height: 32px;
  border-radius: 4px;
  border: 1px solid #424242;
  display: inline-block;
  padding-left: 32px;
  position: relative;
  margin-right: 12px;
}
::v-deep(.ant-input-group-wrapper) {
  display: inline-block;
}
.priceInput {
  width: 632px;
}
@jian: #ec7f8c;
@feng: #f59a23;
@ping: #ffff80;
@gu: #96f203;
@shenGu: #81d3f8;
.labelIdon {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  position: absolute;
  left: 14px;
  top: 12px;
}
.jian {
  background: rgba(236, 127, 140, 0.4);
  color: @jian;
}
.jianBg {
  background: @jian;
}
.jianPen {
  color: @jian;
}
.feng {
  background: rgba(245, 154, 35, 0.4);
  color: @feng;
}
.fengBg {
  background: @feng;
}
.fengPen {
  color: @feng;
}
.ping {
  background: rgba(255, 255, 128, 0.4);
  color: @ping;
}
.pingBg {
  background: @ping;
}
.pingPen {
  color: @ping;
}
.gu {
  background: rgba(150, 242, 3, 0.4);
  color: @gu;
}
.guBg {
  background: @gu;
}
.guPen {
  color: @gu;
}
.shengu {
  background: rgba(129, 211, 248, 0.4);
  color: @shenGu;
}
.shenguBg {
  background: @shenGu;
}
.shenguPen {
  color: @shenGu;
}
.dateTable {
  border: 1px solid #424242;
  border-radius: 4px;
  display: flex;
  flex-wrap: wrap;
  .cell {
    width: 12.5%;
    display: inline-block;
    height: 28px;
    line-height: 28px;
    border: 1px solid #424242;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    user-select: none;
    &::selection {
      background: none;
    }
  }
}
.editIcon {
  font-size: 16px;
  margin-right: 10px;
  cursor: pointer;
}
</style>